package com.hippo.core.core.manager

import android.app.Activity
import android.os.Build
import java.util.Stack

/**
 * Create by Speedy on 2018/7/17
 */
object ActivityStack {

    private val activityStack = Stack<Activity>()


    /**
     * 添加 Activity
     *
     * @param activity
     */
    fun pushActivity(activity: Activity) {
        activityStack.add(activity)
    }

    /**
     * 移除Activity
     *
     * @param activity
     */
    fun popActivity(activity: Activity) {
        activityStack.remove(activity)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (!activity.isDestroyed) {
                activity.finish()
            }
        } else {
            activity.finish()
        }
    }

    /**
     * 移除所有Activity
     */
    fun popAllActivity() {
        while (activityStack.size > 0) {
            activityStack.pop()?.finish()
        }
    }

    fun isActivityRunning(cls: Class<out Activity>): Boolean {
        for (activity in activityStack) {
            if (cls.name == activity.javaClass.name) {
                return true
            }
        }
        return false
    }

    fun getCurrentActivity(): Activity? {
        return activityStack.peek()
    }

    /**
     * 回退至指定的Activity
     * 只有当指定Activity存在栈中才会回退
     * @param cls
     */
    fun popToSpecifyActivity(cls: Class<out Activity>) {
        if (activityStack.any { it::class.java == cls }) {
            while (activityStack.size > 0) {
                val temp = activityStack.peek()
                if (temp.javaClass == cls) {
                    return
                } else {
                    activityStack.pop()
                    temp.finish()
                }
            }
        }
    }
}